package org.aj.common.web.file.service;

import org.aj.common.web.file.bean.FileCheckRule;
import org.springframework.lang.Nullable;

import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;

/**
 * @autor aj
 * @description
 * date  2022/1/220:59
 */
public class DefaultFileCheckServiceImpl implements FileCheckService {

   @Nullable
   private List<FileCheckRule> fileCheckRuleList;

    public DefaultFileCheckServiceImpl(List<FileCheckRule> fileCheckRuleList) {
        this.fileCheckRuleList = fileCheckRuleList;
    }

    public List<FileCheckRule> getFileCheckRuleList() {
        return fileCheckRuleList;
    }

    @Override
    public boolean checkFilePath(String path) {
        boolean present = fileCheckRuleList.stream().filter(fileCheckRule -> fileCheckRule.getPath().equalsIgnoreCase(path)).findAny().isPresent();
        if(present)
            return true;
        return false;
    }

    @Override
    public FileCheckRule getCheckRule(String path) {
        Optional<FileCheckRule> first = fileCheckRuleList.stream()
                .filter(new Predicate<FileCheckRule>() {
                    @Override
                    public boolean test(FileCheckRule fileCheckRule) {
                        return path.equalsIgnoreCase(fileCheckRule.getPath());
                    }
                }).findFirst();
        if(first.isPresent()){
            return first.get();
        }else{
            first = fileCheckRuleList.stream()
                    .filter(new Predicate<FileCheckRule>() {
                        @Override
                        public boolean test(FileCheckRule fileCheckRule) {
                            return "*".equalsIgnoreCase(fileCheckRule.getPath());
                        }
                    }).findFirst();
            if(first.isPresent())
                return first.get();
        }
        return null;
    }
}
